#!/usr/bin/env python
# -*- coding: utf-8 -*-

from utils import log
from sqlalchemy.orm import mapper, sessionmaker
from datetime import datetime
from sqlalchemy import Table, MetaData, Column, ForeignKey, Integer, BigInteger, String, Unicode, UnicodeText, DateTime
from controls.data_pool_mysql import engine

metadata = MetaData()
Session = sessionmaker()
Session.configure(bind=engine)

"""user_base collection has 
   id:         用户id (int)
   username:   用户名 (str)
   password:   密码，明文 (str)
   role:       用户角色（int）
   ctime:      注册时间(datetime)
"""


class ManageUserItem(object):

    def to_dict(self):
        res = {}
        res['id'] = self.id
        res['username'] = self.username
        res['password'] = self.password
        res['role'] = self.role
        res['ctime'] = self.ctime
        return res

    def __repr__(self):
        return "%d" % (self.id)


manage_user_table = Table(
    'manage_user', metadata,
    Column('id', Integer, primary_key=True, autoincrement=True),
    Column('username', Unicode(65), index=True, unique=True, nullable=False),
    Column('password', Unicode(65), nullable=True),
    Column('role', Integer, default=1),
    Column('ctime', DateTime, default=datetime.now, nullable=False),
)

mapper(ManageUserItem, manage_user_table)


def create_manage_user_table_if_not_exist():
    metadata.create_all(engine)

def add_manage_user_item(p_item):
    item = ManageUserItem()
    item.username = p_item['username']
    item.password = p_item['password']
    item.role = p_item['role']
    try:
        session = Session()
        session.add(item)
        session.flush()
        session.commit()
        return True
    except Exception as e:
        log.exp(e)
        session.rollback()
        return False
    finally:
        session.close()


def get_manage_user_by_username(p_username):
    try:
        session = Session()
        item = session.query(ManageUserItem).filter_by(username=p_username).first()
        return item.to_dict()
    except Exception as e:
        log.exp(e)
        session.rollback()
        return None
    finally:
        session.close()


def get_password_by_username(p_username):
    try:
        session = Session()
        item = session.query(ManageUserItem).filter_by(username=p_username).first()
        return item.to_dict()['password']
    except Exception as e:
        log.exp(e)
        session.rollback()
        return None
    finally:
        session.close()

if __name__ == "__main__":
    create_manage_user_table_if_not_exist()
    item = {
        'username': 'shitouren',
        'password': 'chaojishitou',
        'role':1
    }
    add_manage_user_item(item)